package com.sys.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.sys.platform.common.utils.StringUtils;
import com.sys.platform.entity.Camera;
import com.sys.platform.entity.Favorites;
import com.sys.platform.entity.request.Favorites.CameraFavoritesVO;
import com.sys.platform.mapper.CameraMapper;
import com.sys.platform.mapper.FavoritesMapper;
import com.sys.platform.service.IFavoritesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏夹Service业务层处理
 *
 * @author yuanfuqiang
 * @date 2024-08-08
 */
@Slf4j
@Service
public class FavoritesServiceImpl implements IFavoritesService {

    @Autowired
    private FavoritesMapper favoritesMapper;

    @Autowired
    private CameraMapper cameraMapper;


    /**
     * 根据id查询收藏夹下的所有设备
     *
     * @param id
     * @return
     */
    @Override
    public List<CameraFavoritesVO> selectCameraListByFavoriteId(Long id) {
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        List<Favorites> favoritesList = favoritesMapper.selectByParentIds(ids.stream().toArray(Long[]::new));
        //查询收藏夹下的所有设备code
        List<String> idList = new ArrayList<>();
        selectFavoritesOnlyCamera(favoritesList, idList);
        if (StringUtils.isEmpty(idList)) {
            return null;
        }
        idList = idList.stream().distinct().collect(Collectors.toList());
        log.info("查询收藏夹id: {},下的所有设备: {}", id, idList);
        List<Camera> cameraListList = cameraMapper.selectByCameraCodes(idList);
        List<CameraFavoritesVO> cameraFavoritesList = new ArrayList<>();
        //封装返回参数
        cameraListList.stream().forEach(item -> {
            CameraFavoritesVO cameraFavoritesVO = new CameraFavoritesVO();
            BeanUtil.copyProperties(item, cameraFavoritesVO, CopyOptions.create().ignoreNullValue());
            cameraFavoritesList.add(cameraFavoritesVO);
        });
        return cameraFavoritesList;
    }

    /**
     * 查询收藏夹下的设备(仅设备)
     *
     * @param favoritesList
     */
    private void selectFavoritesOnlyCamera(List<Favorites> favoritesList, List<String> idList) {
        favoritesList.stream().forEach(item -> {
            if ((item.getKinds().equals("RTSP") || item.getKinds().equals("GBX"))) {
                idList.add(item.getCameraCode());
            } else {
                Favorites favorites = new Favorites();
                favorites.setParentId(item.getId());
                //查询子收藏夹及设备id
                List<Favorites> list = favoritesMapper.select(favorites);
                if (list.size() > 0) {
                    selectFavoritesOnlyCamera(list, idList);
                }
            }
        });
    }

}
